package cn.nexttec.noteplayer.viewmodels

import android.content.Context
import android.os.Build
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.nexttec.noteplayer.common.NOTE
import cn.nexttec.noteplayer.common.Preference
import cn.nexttec.noteplayer.common.debug
import cn.nexttec.noteplayer.databases.dao.NoteDao
import cn.nexttec.noteplayer.injection.IoDispatcher
import cn.nexttec.noteplayer.models.NoteFile
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import javax.inject.Inject
import javax.inject.Named

@HiltViewModel
class MainViewModel @Inject constructor(
    @ApplicationContext val context: Context,
    val preference: Preference,
    @Named("BaseDir") val noteDir: File,
    val noteDao: NoteDao,
    @IoDispatcher val ioDispatcher: CoroutineDispatcher
) : ViewModel() {

    fun copyMarkdownTutorial() {
        if (noteDir.exists().not()) {
            NOTE debug "创建NoteDir: ${noteDir.absolutePath}"
            noteDir.mkdirs()
        }

        NOTE debug "NoteDir: 是否已创建成功:${noteDir.exists()}"

        NOTE debug "${Build.VERSION.SDK_INT}"
        val tutorialName = "Markdown使用指南.md"
        val markdownTutorial = File(noteDir, tutorialName)

        if (markdownTutorial.exists().not()) {
            viewModelScope.launch(ioDispatcher) {
                context.assets.open(tutorialName).use { input ->
                    FileOutputStream(markdownTutorial).use { output ->
                        input.copyTo(output)
                    }
                }
                val noteFile = NoteFile().apply {
                    name = markdownTutorial.nameWithoutExtension
                    folder = markdownTutorial.parent
                    filepath = markdownTutorial.absolutePath
                }
                noteDao.createNote(noteFile)
                NOTE debug "copy file:${markdownTutorial.absolutePath}"
            }
        } else {
            NOTE debug "file exists:${markdownTutorial.absolutePath}"
        }
    }

}
